import { createSlice } from "@reduxjs/toolkit";

export const authSlice = createSlice({
  name: "auth",
  initialState:()=>{
    const token = localStorage.getItem("token");
    if(!token){
      return{
        isLogged: false,
        token: null,
        expirationTime: 0
      }
    }

    return{
      isLogged: true,
      token,
      expirationTime: +localStorage.getItem("expirationTime")
    }
  },
  reducers:{
    login(state, action){
      state.isLogged = true
      state.token = action.payload.token

      const crrentTime = Date.now()
      const timeout = 1000*60*60*24*7
      state.expirationTime = crrentTime+timeout

      localStorage.setItem("token", state.token);
      localStorage.setItem("expirationTime", state.expirationTime);
    },
    logout(state, action){
      state.isLogged = false
      state.token = null


      localStorage.removeItem("token");
      localStorage.removeItem("expirationTime");
    }
  }
})

export const {login, logout} = authSlice.actions;